<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Drawing Grid Example</title>
	<style>
		#grid, #palette {
			padding: 0px;
			margin: 0;
			border-collapse: collapse;
		}

		#palette td, #grid td {
			width: 20px;
			height: 20px;
		}

		#grid td {
			border: 1px solid #cccccc;
		}
	</style>
	<script src="jquery-1.6.1.js"></script>
	<script>
		$(document).ready(function() {
			//画10×10的表格
			for(i = 0; i < 10; i++) {
				$('#grid').append(
						'<tr>' +
								'<td>&nbsp;</td>' +
								'<td>&nbsp;</td>' +
								'<td>&nbsp;</td>' +
								'<td>&nbsp;</td>' +
								'<td>&nbsp;</td>' +
								'<td>&nbsp;</td>' +
								'<td>&nbsp;</td>' +
								'<td>&nbsp;</td>' +
								'<td>&nbsp;</td>' +
								'<td>&nbsp;</td>' +
						'</tr>'
				);
			}

			$.getJSON('load_drawing.php', function(data) {
				$('#grid td').each(function(index) {
					$(this).css('background-color', data[index]);
				});
			});

			var active_color = 'rgb(0, 0, 0)';
			$('#palette td').each(
					function(index) {
						$(this).bind('click', function() {
							active_color = $(this).css('background-color');
							$('#debug_palette_color').html('active palette color is:' + '<span style="width:20px; height: 20px; background-color:' + active_color + ';">' +active_color + '</span>');
						});
					}
			);

			$('#grid td').each(
					function(index) {
						//绑定onclick事件
						$(this).bind('click', function() {
							$(this).css('background-color', active_color);
						});
					}
			);

			$('#clear').click(function() {
				$('#grid td').css('background-color', 'transparent');
			});

			$('#save').click(function() {
				var colorAsJson = new Object();
				var i = 1;
				$('#grid td').each(function() {
					colorAsJson[i] = $(this).css('background-color');
					i++;
				});

				$.ajax({
					type:'post',
					url:'save_drawing.php',
					dataType:'text',
					data:colorAsJson,
					success:function(data) {
						$('#debug_message').html('saved image');
					},
					failure: function () {
						$('#debug_message').html('An error occured trying save the image');
					}

				});
			});
		});
	</script>
</head>
<body>
	<p><strong>Palette</strong></p>
	<table id="palette">
		<tr>
			<td style="background-color: rgb(0, 0, 0);">&nbsp;</td>
			<td style="background-color: rgb(119, 119, 119);">&nbsp;</td>
			<td style="background-color: rgb(255, 255, 255);">&nbsp;</td>
			<td style="background-color: rgb(255, 0, 0);">&nbsp;</td>
			<td style="background-color: rgb(0, 255, 0);">&nbsp;</td>
			<td style="background-color: rgb(0, 0, 255);">&nbsp;</td>
			<td style="background-color: rgb(255, 255, 0);">&nbsp;</td>
		</tr>
	</table>
	<button id="save">Save</button>
	<button id="clear">Clear</button>
	<p><strong>Draw!</strong></p>
	<table id="grid" cellpadding="0">
	</table>
	<p><em>Debug console:&nbsp;</em></p>
	<div id="debug_message"></div>
	<div id="debug_palette_color"></div>
</body>
</html>